<template>
  <div class='container'>
     <el-card style="margin-top: 10px;">
        <!-- 头部 -->
      <el-row>
        <el-col :span="22">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="学科名称">
              <el-input
                v-model="lineForm.subjectName"
                style="margin-right: 10px"
              ></el-input>
            </el-form-item>
            <el-button size="small" @click="reset">清除</el-button>
            <el-button @click="hSearch" type="primary" size="small"
              >搜索</el-button
            >
          </el-form>
        </el-col>
        <el-col :span="2">
         <el-button
              class="filter-item fr"
              size="small"
              style="margin-left: 10px;"
              @click="hAdd"
              type="success"
              icon="el-icon-edit"
            >添加学科</el-button>
        </el-col>
      </el-row>
          <el-alert
                 :title="`数据一共${total}条`"
                 type="info"
                 show-icon>
           </el-alert>
        <el-table border :data="list">
          <el-table-column label="序号"  type="index" width="50"/>
          <el-table-column label="学科名称"  prop="subjectName"/>
          <el-table-column label="创建者" prop="username"/>
          <el-table-column label="创建日期" prop="addDate">
            <template #default={row}>
              {{formatDate(row.addDate)}}
            </template>
          </el-table-column>
          <el-table-column label="前台是否显示" prop="isFrontDisplay">
            <template #default = {row}>
               {{isShow(row.isFrontDisplay)}}
            </template>
          </el-table-column>
          <el-table-column label="二级目录" prop="twoLevelDirectory" />
          <el-table-column label="标签" prop="tags" />
           <el-table-column label="题目数量" prop="totals" />
          <el-table-column label="操作" width="280px">
            <template #default="{row}">
              <el-button type="text" size="medium" @click="$router.push(`/subjects/directorys?id=${row.id}&name=${row.subjectName} `)">学科分类</el-button>
               <el-button type="text" size="medium" @click="$router.push(`/subjects/tags?id=${row.id}&name=${row.subjectName}`)">学科标签</el-button>
              <el-button type="text" size="medium" @click="hEdit(row)">修改</el-button>
              <el-button type="text" size="medium" @click="hDel(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
          <el-pagination
           background
           :current-page="params.page"
           :page-sizes="[2,5,10, 15, 20]"
           :page-size="params.pagesize"
            layout="prev, pager, next,sizes,jumper"
           :total="total"
           @size-change="handleSizeChange"
           @current-change="handleCurrentChange"
           />
      </el-card>
      <el-dialog :visible.sync="showDialog" :title="isEdit ? '修改学科':'添加学科'" @closed="resetForm">
      <el-form ref="addForm" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="新增学科" prop="subjectName">
        <el-input v-model="formData.subjectName" style="width:50%" placeholder="请输入学科名称" />
    </el-form-item>
     <el-form-item >
      <el-switch
        v-model="formData.isFrontDisplay"
        active-text="显示"
        active-value= "1"
        inactive-text="不显示"
        inactive-value= "0"
      />
    </el-form-item>
  </el-form>

  <template #footer>
    <div style="text-align: right;">
      <el-button @click="showDialog = false">取消</el-button>
      <el-button type="primary" @click="hSubmit">确定</el-button>
    </div>
  </template>
      </el-dialog>
  </div>
</template>

<script>
// import moment from 'moment'
import { subList, remove, add, update } from '@/api/hmmm/subjects.js'
export default {
  data () {
    return {
      list: [],
      isEdit: false,
      lineForm: {
        page: 1,
        pagesize: 10,
        subjectName: ''
      },
      formData: {
        subjectName: '',
        isFrontDisplay: '1'
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      },
      showDialog: false,
      total: 0,
      params: {
        page: 1,
        pagesize: 10
        // subjectName: ''
      }
    }
  },
  created () {
    this.loadSubjectList()
  },
  methods: {
    formatDate (value) {
      return this.moment(value).format('YYYY-MM-DD HH:mm:ss')
    },
    reset () {
      this.lineForm = {
        page: 1,
        pagesize: 10,
        subjectName: ''
      }
      this.lineForm.page = 1
      this.loadSubjectList()
    },
    hSearch () {
      this.doSearch()
    },
    async doSearch () {
      const res = await subList(this.lineForm)
      console.log(res, 'searchSubList')
      this.list = res.data.items
      this.total = res.data.counts
    },
    isShow (id) {
      return id === 1 ? '是' : '否'
    },
    resetForm () {
      this.$refs.addForm.resetFields()
      this.formData = {
        subjectName: '',
        isFrontDisplay: '1'
      }
    },
    hSubmit () {
      this.$refs.addForm.validate(valid => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    async  doEdit () {
      try {
        const res = await update(this.formData)
        console.log(res)
        if (res.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功！')
        this.showDialog = false
        this.loadSubjectList()
      } catch (error) {
        console.log(error)
      }
    },
    async  doAdd () {
      try {
        const res = await add(this.formData)
        console.log(res)
        if (res.status !== 200) return this.$message.error('添加失败')
        this.$message.success('添加成功！')
        this.showDialog = false
        this.params.page = 1
        this.loadSubjectList()
      } catch (error) {
        console.log(error)
      }
    },
    hAdd () {
      this.isEdit = false
      this.showDialog = true
    },
    hEdit (row) {
      this.isEdit = true
      this.showDialog = true
      this.formData = { ...row }
    },
    hDel (row) {
      this.$confirm('你确定删除该学科吗?').then(async () => {
        const res = await remove(row)
        console.log(res, 'remove')
        if (this.list.length === 1) {
          this.params.page--
          if (this.params.page <= 0) {
            this.params.page = 1
          }
        }
        if (res.status === 200) {
          this.$message.success('删除成功！')
        }
        this.loadSubjectList()
      }).catch(error => {
        console.log(error)
      })
    },
    async loadSubjectList () {
      try {
        const res = await subList(this.params)
        console.log(res)
        this.$message.success('加载学科列表成功')
        this.list = res.data.items
        this.total = res.data.counts
      } catch (err) {
        console.log(err)
        this.$message.error('加载学科列表数据失败')
      }
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.params.page = 1
      this.params.pagesize = val
      this.loadSubjectList()
    },
    async handleCurrentChange (val) {
      if (this.lineForm.subjectName === '') {
        this.params.page = val
        this.loadSubjectList()
      } else {
        this.lineForm.page = val
        // const res = await subList(this.lineForm)
        // console.log(res, 'directorylist')
        // this.list = res.data.items
        // this.total = res.data.counts
        this.doSearch()
      }
      // console.log(`当前页: ${val}`)
      // this.params.page = val
      // this.loadSubjectList()
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  margin-top: 1px;
  margin-bottom: 10px;
  ::v-deep .el-input__inner{
    height: 32px;
  }
   .el-button {
    margin: 0px 5px;
  }
  .el-alert{
    margin-bottom: 20px;
    // margin-top: 5px;
  }
  .el-pagination {
    text-align: right;
    margin-top: 20px;
  }
}
</style>
